package com.leetcode.string;

/**
 * @author Dennis Li
 * @date 2020/9/8 19:54
 */
public class DecodeString_394 {

    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            if (isNumber(s.charAt(i))) {
                i = getPattern(s, sb, i);
            } else {
                sb.append(s.charAt(i));
            }
        }

        return sb.toString();
    }

    private int getPattern(String s, StringBuilder sb, int i) {
        int temp = s.indexOf('[', i);
        int times = Integer.parseInt(s.substring(i, temp));
        i = temp + 1; // 跳过 '['
        StringBuilder pattern = new StringBuilder();
        while (s.charAt(i) != ']') {
            if (isNumber(s.charAt(i))) {
                i = getPattern(s, pattern, i) + 1;
            } else {
                pattern.append(s.charAt(i++));
            }
        }
        for (int j = 0; j < times; j++) {
            sb.append(pattern);
        }
        return i;
    }

    private boolean isNumber(char ch) {
        return ch >= '1' && ch <= '9';
    }

    public static void main(String[] args) {
        DecodeString_394 ans = new DecodeString_394();

        String decodeString = ans.decodeString("3[a2[c]]");

        System.out.println(decodeString);
    }

}
